<template>
  <div>
    <el-card class="cardTits" shadow="hover">
      <div class="subject-title">
        <div class="query query-subject">
          <div class="flex-box">
            <div class="query-input">
              <el-input
                placeholder="ID/任务名称"
                v-model="searchVal"
              ></el-input>
            </div>
            <div class="query-date" v-if="taskType == 1">
              <el-date-picker
                v-model="date"
                type="daterange"
                range-separator="～"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              >
              </el-date-picker>
            </div>
            <el-button @click="getTableList" class="query-btn" type="primary">查询</el-button>
          </div>
          <div class="flex-box" v-if="taskType == 0" style="margin-right: 20px">
            <el-button
            @click="addTaskModules = true"
            class="query-btn task-add"
            ><i class="el-icon-upload"></i> Excel批量验收</el-button
            >
            <!-- <el-upload
              action="#"
              :on-change="handleChangeFile"
              list-type="picture-card"
              :multiple="false"
              :show-file-list="false"
              class="upload-yanshou"
              :http-request="batchUpdateTask"
            >
              <el-button class="query-btn" type="primary">批量验收通过</el-button>
            </el-upload>
            <el-button @click="downloadBatchTCheckTemplate" class="query-plain" plain>
              <i class="el-icon-upload"></i>
              下载批量验收模板
            </el-button> -->
          </div>
        </div>
      </div>
      <el-table
        :data="tableData"
        @selectionChange="downloadWhether"
        stripe
        style="width: 100%"
        ref="multipleTable"
        @sort-change="sortChange"
      >
        <!-- <el-table-column type="selection" width="60"> </el-table-column> -->
        <el-table-column width="30"> </el-table-column>
        <el-table-column prop="id" sortable="custom" label="序号" width=""> </el-table-column>
        <el-table-column prop="taskId" sortable="custom" label="任务ID" width=""> </el-table-column>
        <el-table-column prop="name" sortable="custom" label="任务名称" min-width="100">
        </el-table-column>
        <el-table-column prop="taskPayment" sortable="custom" label="预估服务费" min-width="110">
          <template #default="item">
            {{ formatNumber(item.row.taskPayment) }}
          </template>
        </el-table-column>
        <el-table-column prop="legalName" sortable="custom" label="任务接收人" min-width="110">
        </el-table-column>
        <el-table-column prop="legalPhone" sortable="custom" label="任务接收人手机号" width="150">
        </el-table-column>
        <el-table-column prop="bonus" sortable="custom" label="奖励" width="">
          <template #default="item">
            {{ formatNumber(item.row.bonus) }}
          </template>
        </el-table-column>
        <el-table-column prop="fine" sortable="custom" align="center" label="惩罚">
          <template #default="item">
            {{ formatNumber(item.row.fine) }}
          </template>
        </el-table-column>
        <el-table-column prop="expectProfit" sortable="custom" align="center" min-width="110" label="实际服务费">
          <template #default="item">
            <template v-if="item.row.inspectedStatus == 1">
              {{ formatNumber(item.row.expectProfit) }}
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column prop="releaseDate" sortable="custom" label="任务开始时间" min-width="120">
          <template #default="item">
            {{ format("yyyy-MM-dd", new Date(item.row.releaseDate)) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" sortable="custom" label="任务结束时间" min-width="120">
          <template #default="item">
            {{ format("yyyy-MM-dd", new Date(item.row.endDate)) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="附件" width="">
          <template #default="item">
            <span v-if="item.row.enclosureUrl == null || item.row.enclosureUrl == ''">--</span>
            <el-button v-else style="color:#326CF0;font-size:12px" type="text" @click="openUrl(item.row.enclosureUrl)">查看附件</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="inspectedStatus" label="状态" width="">
          <template #default="item">
            {{ inspectedStatus[item.row.inspectedStatus] }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          class-name="editor"
        >
          <template #default="item">
            <el-button @click="addTaskDetails(item.$index)" type="text">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="tableData.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="arrPage"
        :page-size="selectPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 详情弹出层 -->
    <el-dialog title="任务详情" custom-class="task-dialog" v-model="addTaskModule" width="600px">
      <div class="add-border"></div>
      <div class="add-task" v-if="checkid != null">
        <el-form
          ref="taskForm"
          label-width="150px"
          class="demo-ruleForm"
          :model="taskForm"
          :rules="rules"
        >
          <el-form-item label="任务名称">
            <el-input v-model="tableData[checkid].name" disabled></el-input>
          </el-form-item>
          <el-form-item label="预估服务费">
            <el-input v-model="tableData[checkid].taskPayment" disabled></el-input>
          </el-form-item>
          <el-form-item label="任务地址">
            <el-input v-model="tableData[checkid].taskAddress" disabled></el-input>
          </el-form-item>
          <el-form-item label="任务开始时间">
            <el-form-item prop="startTime">
              <el-date-picker
                type="date"
                disabled
                placeholder="选择日期"
                v-model="tableData[checkid].takeTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="任务结束时间">
            <el-form-item prop="endTime">
              <el-date-picker
                type="date"
                disabled
                placeholder="选择日期"
                v-model="tableData[checkid].endDate"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <template v-if="tableData[checkid].inspectedStatus == 1">
            <!-- 验收通过 -->
            <el-form-item label="奖励">
              <el-input ref="bonus" v-model="tableData[checkid].bonus" disabled></el-input>
            </el-form-item>
            <el-form-item label="处罚">
              <el-input ref="fine" v-model="tableData[checkid].fine" disabled></el-input>
            </el-form-item>
            <el-form-item label="实际服务费">
              <el-input v-model="tableData[checkid].expectProfit" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="desc">
              <el-input type="textarea" disabled v-model="tableData[checkid].remarks"></el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="奖励">
              <el-input ref="bonus" v-model="taskForm.bonus" disabled></el-input>
            </el-form-item>
            <el-form-item label="处罚">
              <el-input ref="fine" v-model="taskForm.fine" disabled></el-input>
            </el-form-item>
            <el-form-item label="实际服务费" prop="servicePayment">
              <el-input @input="servicePaymentChange" v-model="taskForm.servicePayment"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="desc">
              <el-input type="textarea" v-model="taskForm.desc"></el-input>
            </el-form-item>
          </template>
          <el-form-item label="附件">
            <span v-if="tableData[checkid].enclosureUrl == null  || tableData[checkid].enclosureUrl == ''">--</span>
            <el-button v-else class="query-plain" @click="openUrl(tableData[checkid].enclosureUrl)" plain> 查看附件 </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add-border"></div>
      <!-- <template #footer> -->
        <div class="dialog-footer" style="padding-bottom: 20px;text-align:right">
          <el-button v-if="tableData[checkid].inspectedStatus != 1" type="primary" @click="updateTaskInspectedStatus(1)"
            >验收通过</el-button
          >
          <el-button v-if="tableData[checkid].inspectedStatus != 1" type="warning" @click="updateTaskInspectedStatus(2)"
            >驳回</el-button
          >
          <el-button @click="addTaskModule = false">取 消</el-button>
        </div>
      <!-- </template> -->
    </el-dialog>

    <!-- 批量验收弹出层 -->
    <el-dialog title="批量验收" custom-class="task-margin" v-model="addTaskModules" @close="taskClose" width="600px">
      <div class="add-task">
        <el-form
          :model="taskForm"
          :rules="rules"
          v-if="addTaskModules"
          ref="taskForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item>
            <el-upload
              ref="upload"
              name="excel"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
              accept=".xlsx, .xls"
              action="#"
              :file-list="fileList"
              :on-change="xlsxFilelist"
              :on-remove="deleteXlsxfile"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <div class="el-upload__tip text-center">
              <span style="margin-left: 60px">仅允许导入xls、xlsx格式文件。</span>
              <span style="cursor: pointer;color: #326cf0;" @click="downloadBatchTCheckTemplate">下载模板</span>
            </div>
          </el-form-item>
          <div class="cardTits renwu-error" v-if="mubanflag">
            <div class="renwu-title">数据问题：</div>
            <el-table
              :data="mubanArr"
              stripe
              max-height="200"
              style="width: 100%"
            >
              <el-table-column prop="name" label="姓名"></el-table-column>
              <el-table-column prop="idcard" min-width="150" label="身份证号"></el-table-column>
              <el-table-column prop="failReason" label="原因"></el-table-column>
            </el-table>
            <span class="renwu-dwoload" @click="loadfile">异常人员名单下载</span>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTaskModules = false">取 消</el-button>
          <el-button type="primary" @click="addTaskMethods"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: "AcceptanceTaskTable",
  props: ["taskType"],
  data() {
    return {
      orderByZH: false,
      orderByAsc: false,
      orderByColume: 'createTime',
      searchVal: "", // 查询条件
      total: 1, // 总条数
      arrPage: [10, 20], // 每页条数
      selectPage: 10, // 每页选中条数
      currentPage: 1,
      date: "",
      selectValue: "",
      addTaskModule: false,
      addTaskModules: false,
      mubanflag: false,
      mubanArr: [],
      mubanUrl: "",
      fileList: [],
      tableData: [],
      taskForm: {
        desc: "", // 任务名称
        servicePayment: "", // 实际服务款
        bonus: 0,
        fine: 0
      },
      rules: {
        servicePayment: [
          { required: true, message: "请输入实际任务服务费", trigger: "blur" },
        ]
      },
      inspectedStatus: {
        0: '待验收',
        1: '验收通过',
        2: '验收驳回',
      },
      checkid: null,
      fileData: '',
    };
  },
  components: {},
  mounted() {
    this.getTableList()
  },
  methods: {
    downloadWhether(d) {
      // 表格复选 选择回调
      console.log(d);
    },
    handleCurrentChange(d) {
      // 分页切换回调
      this.currentPage = d
      this.getTableList()
    },
    handleSizeChange(d) {
      // 分页切换每页条数回调
      this.selectPage = d
      this.getTableList()
    },
    getTableList() {
      // 获取任务验收列表信息
      let start = "",
          end = ""
      if(this.date) {
        start = this.date[0]
        end = this.date[1]
      }
      this.$http({
        url: "/api/quick/business/task/inspectedTasks",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          inspectedStatus: this.taskType, // 验收状态
          isComplete: '',
          startDate: start,
          endDate: end,
          mixedStr: this.searchVal,
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code == 0) {
          this.tableData = data.result.list
          this.total = data.result.total
        }
      });
    },
    sortChange(d) {
      // 监听排序
      if(d.prop == null) {
        // 默认排序方式
        this.orderByZH = false
        this.orderByAsc = false
        this.orderByColume = 'createTime'
      }else {
        let orderByZH = false
        if(d.prop == "name" || d.prop == 'legalName') {
          orderByZH = true
        }
        this.currentPage = 1
        this.selectPage = 10
        let orderByAsc = d.order == "descending" ? false : true
        this.orderByZH = orderByZH
        this.orderByAsc = orderByAsc
        this.orderByColume = d.prop
      }
      this.getTableList()
    },
    openUrl(url) {
      let newwin = window.open();
      newwin.document.write("<img src=" + url + " />");
    },
    addTaskDetails(id) {
      this.checkid = id
      this.addTaskModule = true
      this.taskForm = {
        desc: "", // 任务名称
        servicePayment: "", // 实际服务款
        bonus: 0,
        fine: 0
      }
      console.log(this.taskForm)
    },
    xlsxFilelist(file) {
      this.fileList = [file]
    },
    deleteXlsxfile() {
      this.fileList = []
    },
    addTaskMethods() {
      // 新建任务
      if(this.fileList.length == 0) {
        this.$message({
          message: '请选择上传人员列表',
          type: 'error',
          offset: 60
        })
        return false
      }
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          let file = new FormData()
          file.append("file", this.fileList[0].raw)
          this.$http({
            url: "/api/quick/business/task/batchUpdateTask",
            method: "post",
            headers: {
              "Content-Type": "multipart/form-data",
            },
            data: file
          }).then((data) => {
            if (data.code == 0) {
              if(data.result == '批量审批通过') {
                this.addTaskModule = false
                this.$message({
                  message: '批量验收成功',
                  type: 'success',
                  offset: 60
                })
                this.addTaskModules = false
                this.getTableList()
              }else {
                this.$message({
                  message: '批量验收失败！人员表数据异常！',
                  type: 'error',
                  offset: 60
                })
                this.mubanArr = data.result.data
                this.mubanflag = true
                this.mubanUrl = data.result.url
              }
            }
          });
        } else {
          return false;
        }
      });
    },
    taskClose() {
      // 关闭新建任务清除数据
      this.mubanUrl = ""
      this.mubanflag = false
      this.mubanArr = []
    },
    loadfile() {
      window.open(this.mubanUrl)
    },
    downloadBatchTCheckTemplate() {
      // 下载批量审批模板
      let info = JSON.parse(localStorage.getItem("bussines_info"))
      axios({
        method: "GET",
        url: "/api/quick/task/manage/downloadBatchTCheckTemplate",
        responseType: "blob",
        headers: {
          "websiteName": window.location.host,
          "Authorization": localStorage.getItem("bussines_token"),
          "businessId": info.businessId,
          "businessNo": info.businessNo,
          "platformId": info.platformId,
          "platformNo": info.platformNo,
          "businessType": 3
        }
      })
      .then((res) => {
        const blob = new Blob([res.data]);
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        //后台再header中传文件名
        downloadElement.href = href;
        downloadElement.download = "批量验收模板.xlsx"
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      })
      .catch((err) => {
        console.log(err);
      });
    },
    batchUpdateTask() {
      // 批量验收
      let formObj = new FormData()
      formObj.append('file', this.fileData)
      this.$http({
        url: "/api/quick/business/task/batchUpdateTask",
        method: "post",
         headers: {
          "content-type": "multipart/form-data",
        },
        data: formObj
      }).then((data) => {
        this.fileData = ''
        if (data.code == 0) {
          this.getTableList()
          this.$message({
              message: '验收成功',
              type: 'success'
            });
        }
      }).catch(() => {
        this.fileData = ''
        this.$message({
              message: '验收失败',
              type: 'success'
            });
      })
    },
    handleChangeFile(file) {
      this.fileData = file.raw;
    },
    updateTaskInspectedStatus(status) {
      // 任务验收 通过/驳回
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          this.$http({
            url: "/api/quick/business/task/updateTaskInspectedStatus",
            method: "post",
            headers: {
              "content-type": "application/json",
            },
            data: {
              "id": this.tableData[this.checkid].id,
              "inspectedStatus": status,
              "inspectedMsg": this.taskForm.desc,
              "expectProfit": this.taskForm.servicePayment
            }
          }).then((data) => {
            this.addTaskModule = false
            if (data.code == 0) {
              this.$message.success("验收成功");
              this.getTableList()
            }
          }).catch(() => {
          })
        }
      })
      
    },
    servicePaymentChange(val) {
      // 输入实际服务费
      if(val >= this.tableData[this.checkid].taskPayment) {
        // this.$refs.fine.input.value = 0
        this.taskForm.fine = 0
        // 12998.2
        this.taskForm.bonus = this.cut(val, this.tableData[this.checkid].taskPayment)
        // this.$refs.bonus.input.value = val - this.tableData[this.checkid].taskPayment
      }else {
        // this.$refs.bonus.input.value = 0
        // this.$refs.fine.input.value = this.tableData[this.checkid].taskPayment - val
        this.taskForm.bonus = 0
        this.taskForm.fine = this.cut(this.tableData[this.checkid].taskPayment, val)
      }
    },
    cut(arg1, arg2) {
      // 解决减法计算精度丢失问题
      var r1, r2, m, n;
      try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
      try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
      m = Math.pow(10, Math.max(r1, r2));
      //last modify by deeka
      //动态控制精度长度
      n = (r1 >= r2) ? r1 : r2;
      return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }
  },
};
</script>
<style lang="scss" scoped>
.el-upload-dragger .el-upload__text em {
  color: #326cf0;
  font-style: normal;
}
.downLoadCss {
  font-size: 12px;
    color: #326cf0;
    top: 7px;
    cursor: pointer;
    float: left;
    margin-left: -100px;
    position: relative;
    z-index: 1111;
} 
.cardTits.renwu-error .renwu-dwoload {
    color: #326CF0;
    margin-top: 10px;
    font-size: 12px;
    display: inline-block;
    cursor: pointer;
}
.renwu-error {
    margin: 0 30px 0 80px;
}
.cardTits.renwu-error .renwu-title {
    margin-bottom: 10px;
}
.upload-renyuanbiao {
  float: left;
  margin-left: 100px;
  width: 250px !important;
}
.upload-yanshou {
  margin-right: 20px;
  & :deep(.el-upload) {
    width: auto;
    background-color: #ffffff;
    border: 0;
    height: 32px;
    line-height: 32px;
    .el-button {
      line-height: normal;
    }
  }
}
.task-dialog {
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
    .add-border {
      height: 1px;
      margin-bottom: 30px;
      background-color: #EEF4FB;
    }
  }
}
.query-subject {
  justify-content: space-between;
  align-items: center;
  .flex-box {
    display: flex;
  }
  .task-add {
    margin-right: 20px;
    & :deep(span),
    & :deep(i) {
      color: #ffffff;
    }
  }
  .query-date {
    height: 32px;
    margin-right: 10px;
    & :deep(.el-input__inner) {
      height: 32px;
      border-color: #eff4fa;
      .el-range-input {
        font-size: 12px;
      }
      .el-range__icon,
      .el-range-separator {
        line-height: 24px;
      }
    }
  }
}
.add-task {
  padding-right: 50px;
  & :deep(.el-form-item) {
    .el-date-editor--date {
      .el-input__inner {
        padding: 0 30px;
      }
    }
  }
  & :deep(.el-upload--text) {
    width: auto;
    height: auto;
    border: 0;
    display: block;
    text-align: left;
  }
  & :deep(.el-button--small) {
    color: #326cf0;
    border-color: #326cf0;
  }
}
.cardTits {
  & :deep(.el-card) {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    border: 0;
  }
}
</style>